package com.atguigu.tingshu.user.context;

import com.atguigu.tingshu.user.strategy.UpdateUserPaidRecordStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component      // 策略接口实现类的管理类
public class UpdateUserPaidRecordStrategyContext implements ApplicationContextAware {

    private static final Map<String , UpdateUserPaidRecordStrategy> STRATEGY_MAP = new HashMap<String , UpdateUserPaidRecordStrategy>();

    // 根据付款项目的类型获取策略实现类对象
    public static UpdateUserPaidRecordStrategy getUpdateUserPaidRecordStrategy(String itemType) {
        return STRATEGY_MAP.get(itemType) ;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.getBeansOfType(UpdateUserPaidRecordStrategy.class).values().forEach(strategy -> {
            String itemType = strategy.getItemType();
            STRATEGY_MAP.put(itemType , strategy) ;
        }) ;
    }
}
